package com.hp.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hp.utils.QiniuUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@MultipartConfig
@WebServlet(name = "FileUploadServlet", value = "/fileUploadServlet")
public class FileUploadServlet extends HttpServlet {
    private ObjectMapper mapper = new ObjectMapper();

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        //获得表单提交的数据封装
        Part part = req.getPart("file");
        //获得文件名
        String fileName = part.getSubmittedFileName();
        //获得上传输入流
        InputStream is = part.getInputStream();
        Map<String, Object> map = QiniuUtils.upload(is, fileName);
        //返回JSON
        String json = mapper.writeValueAsString(map);
        resp.getWriter().print(json);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
